package com.net.xpay.common.service.impl;

import com.net.xpay.common.domain.partner.Partner;
import com.net.xpay.common.domain.partner.PartnerAccount;
import com.net.xpay.common.domain.partner.PartnerAccountDetail;
import com.net.xpay.common.domain.partner.PartnerAccountLog;
import com.net.xpay.common.validator.PartnerAccountValidator;
import com.net.xpay.core.enums.PayStatus;
import com.net.xpay.common.manager.partner.PartnerAccountDetailManager;
import com.net.xpay.common.manager.partner.PartnerAccountLogManager;
import com.net.xpay.common.manager.partner.PartnerAccountManager;
import com.net.xpay.common.service.PartnerAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 2020/5/11 11:57

 */
@Slf4j
@Service
@Transactional(transactionManager = "xpayCommonTransactionManager", rollbackFor = Exception.class)
public class PartnerAccountServiceImpl implements PartnerAccountService {

    @Autowired
    private PartnerAccountValidator partnerAccountValidator;

    @Autowired
    private PartnerAccountDetailManager partnerAccountDetailManager;

    @Autowired
    private PartnerAccountManager partnerAccountManager;

    @Autowired
    private PartnerAccountLogManager partnerAccountLogManager;

    @Override
    public void onPay(Partner partner, PartnerAccount account, PartnerAccountDetail detail) {
        partnerAccountValidator.validateAccountEnough(account, detail);

        onFinishAccountPay(partner, account, detail);
    }

    private void onFinishAccountPay(Partner partner, PartnerAccount account, PartnerAccountDetail detail) {
        detail.setPayStatus(PayStatus.PAYED);
        detail.setEndTime(LocalDateTime.now());
        partnerAccountDetailManager.save(detail);

        PartnerAccountLog accountLog = PartnerAccountLog.getInstance(partner, detail);
        accountLog.setChange(detail.getAccountMoney());
        accountLog.setBeforeAmount(account.getMoneyLeft());
        accountLog.setAfterAmount(account.getMoneyLeft() + detail.getAccountMoney());
        partnerAccountLogManager.save(accountLog);

        account.setMoneyLeft(account.getMoneyLeft() + detail.getAccountMoney());
        partnerAccountManager.updateByPrimaryKeyWithVersion(account);
    }
}
